package servlet.User;

import DAO.UserDAO;
import Model.User;
import appexception.AppException;
import service.BaseService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @program: wsn_blog
 * @description
 * @author:王松年
 * @creat: 2021-07-12 10:46:37
 **/

@WebServlet("/register")
public class UserRegisterServlet extends BaseService {
    @Override
    protected void query(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        //将注册信息传入的json字符串转为用户
        User registerUser = objectMapper.readValue(req.getInputStream(), User.class);
        if (registerUser.getUsername()==null || registerUser.getUsername().length()==0){
            throw new AppException("REGISTER001", "请输入用户名");
        }
        if (registerUser.getPassword()==null||registerUser.getPassword().length()==0){
            throw new AppException("REGISTER002", "请输入密码");
        }
        //根据用户查询
        User query = UserDAO.selectByUser(registerUser);
        //查询结果不为空，说明用户存在，不能注册
        if (query != null) {
            throw new AppException("REGISTER003", "用户已存在，请换个用户名或直接登录！");
        }
        //注册用户
        int i = UserDAO.register(registerUser);
        if (i != 1) {//i不等于1，说明插入数据库操作失败
            throw new AppException("REGISTER004", "注册失败，请重试！");
        }
    }
}